<?php

use think\Model;
use think\Request;

class weixin extends Model{
	//回调地址
	public $returnUrl;
	// 应用id
	public $appId;
	// 应用密室
	public $appSecret;

	/**
     * 构造函数
     */
	public function __construct(){
		$this->returnUrl 	= 'http://'.$_SERVER['HTTP_HOST'].'/index.php/book/member.login/callback/oauth/weixin';
		$this->appId 		= '';
		$this->appSecret 	= '';
	}

	//构造要请求的参数数组，无需改动
	public function login(){
		// 第一步：请求CODE
		$_SESSION['state'] = md5(uniqid(rand(), TRUE));
		//拼接URL
		$dialog_url = "https://open.weixin.qq.com/connect/qrconnect?"
			. "appid=".$this->appId
			. "&redirect_uri=".urlencode($this->returnUrl)
			. "&response_type=code"
			. "&scope=snsapi_login"
			. "&state=".$_SESSION['state'];
		echo("<script> top.location.href='" . $dialog_url . "'</script>");
		exit;
	}

    /**
     * 微信 登录返回  参考手册 
     * @return boolean
     */
	public function respon(){
		// 第二步：通过code获取access_token
		if($_REQUEST['state'] == $_SESSION['state']){
			$code = $_REQUEST["code"];
			//拼接URL
			$token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?"
				. "appid=" . $this->appId
				. "&secret=" . $this->appSecret
				. "&code=" . $code
				. "&grant_type=authorization_code";
				
			// 获取 Access Token
			$response = json_decode($this->get_contents($token_url));
			if (isset($response->error)){
				echo "<h3>error:</h3>" . $response->error;
				echo "<h3>msg  :</h3>" . $response->error_description;
				exit;
			}

			// 第三步：通过access_token获取用户信息
			$user_info_url = "https://api.weixin.qq.com/sns/userinfo?".http_build_query(['access_token' => $response->access_token, 'openid' => $response->openid]);
			$user_info  = json_decode($this->get_contents($user_info_url));
			if (isset($user_info->error))
			{
				echo "<h3>error:</h3>" . $user_info->error;
				echo "<h3>msg  :</h3>" . $user_info->error_description;
				exit;
			}
			$_SESSION['state'] = null; // 验证SESSION
			return [
				'openid' 	=> $user_info->openid,// weixin openid
				'oauth' 	=> 'weixin',
				'nickname' 	=> $user_info->nickname,
				'avatar' 	=> $user_info->headimgurl,
				'unionid' 	=> $user_info->unionid
			];

			halt($user_info);
		}else{
			return false;
		}
	}

	public function get_contents($url, $method_post = 0){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_POST, $method_post);
		$response =  curl_exec($ch);
		curl_close($ch);

		//-------请求为空
		if(empty($response)){
			exit("50001");
		}
		return $response;
	}
}